rm(list= ls())

library(tidyverse)

## County level election data 

county_elec <- read_rds('data/elections_federal_county_94_17.rds') %>% 
  filter(lubridate::year(date)  == 2013) %>% 
  mutate(left_total_party  = greens + spd + left) %>% #
  dplyr::select(ags, left_total_party)

## Load county covars and merge

countycovs <- read_rds("data/countycovs_germany_2015.rds")

countycovs <- countycovs %>% 
  left_join(county_elec, by = c('county_id' = 'ags'))

## Define Covariates 

covs <- c('unemp_rate_nat', 'foreign_share', 'left_total_party')

## Standardize 

countycovs <- countycovs %>% 
  mutate_at(covs, scale) %>% 
  filter(state_id %in% c('05', '09'))

## Get balance balance 

balance <- lapply(covs, function(cov){
  
  f <- as.formula(paste0(cov, " ~", 'treated + state_id'))
  
  lm(f, data = countycovs) %>%
    tidy(conf.int = T) %>%
    filter(term == 'treated') %>%
    mutate(covariate = cov)
  
}) %>%
  reduce(rbind) %>%
  mutate(covariate = recode(covariate,
                            'left_total_party' = 'Total left vote (2013)',
                            'unemp_rate_nat' = 'Unemployment rate',
                            'foreign_share' = 'Share of foreigners'))

## Plot This 

ggplot(balance, aes(x = covariate,
                    y = estimate,
                    ymin = conf.low,
                    ymax = conf.high)) +
  geom_errorbar(width = 0) + 
  geom_point(shape = 21, fill = 'white', size = 2) + 
  theme_bw() + 
  geom_hline(yintercept = 0, linetype = 'dotted') + 
  coord_flip() + 
  labs(y = 'Standardized difference',
       x = '')
